package com.lv.test.controller;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.common.TreeChildCount;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.cgform.service.impl.config.util.DbTableUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import java.io.OutputStream;
import org.jeecgframework.core.util.BrowserUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.SessionFactory;
import org.jeecgframework.core.util.ResourceUtil;
import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Map;
import java.util.HashMap;
import org.jeecgframework.core.util.ExceptionUtil;

import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lv.test.entity.QuestionConfigEntity;
import com.lv.test.entity.QuestionSelectesEntity;
import com.lv.test.entity.TestQuestionEntity;
import com.lv.test.service.QuestionConfigServiceI;
import com.lv.test.service.QuestionSelectesServiceI;
import com.lv.test.service.TestQuestionServiceI;
import com.sun.star.uno.RuntimeException;

/**   
 * @Title: Controller  
 * @Description: 问卷调查配置表
 * @author onlineGenerator
 * @date 2017-05-16 09:36:21
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/questionConfigController")
public class QuestionConfigController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(QuestionConfigController.class);

	@Autowired
	private QuestionConfigServiceI questionConfigService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	@Autowired
	private TestQuestionServiceI testQuestionS;
	@Autowired
	private QuestionSelectesServiceI questionSelectS;
	@Autowired
	@Qualifier("jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private SessionFactory sessionFactory;
	


	/**
	 * 问卷调查配置表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("lv/questionConfigList");
	}
	
	
	@RequestMapping(params="looksPage")
	public ModelAndView lookPage1(HttpServletRequest request){
		request.setAttribute("selectId", request.getParameter("selectId"));
		ModelAndView view = new ModelAndView("lv/looksPage");
		return view;
	}
	
	/**
	 * @param id  问卷配置id
	 * @param request
	 * @param response
	 * @return  预览数据
	 */
	@RequestMapping(params="createPageDate")
	@ResponseBody
	public JSONObject createPageDate(String selectId,HttpServletRequest request, HttpServletResponse response){
		JSONObject jb = new JSONObject();
		selectId = request.getParameter("selectId");
		//获取数据  组装json
		QuestionConfigEntity questionConfig = systemService.getEntity(QuestionConfigEntity.class, selectId);
		jb.put("title",questionConfig.getBpmTitle() );
		JSONArray jsArray = new JSONArray();
		//问题列表
		List<TestQuestionEntity> questions = systemService.findHql(" from TestQuestionEntity where by1 ='"+questionConfig.getId()+"'");
		for(TestQuestionEntity question : questions){
			List<QuestionSelectesEntity> selectes = systemService.findHql(" from QuestionSelectesEntity where by1 = '"+question.getId()+"'");
			JSONObject jsob = new JSONObject();
			jsob.put("questionType",question.getQuestionType() );
			jsob.put("questionRe", question.getQuestionRe());
			jsArray.add(jsob);
			JSONArray selectsArray = new JSONArray();
			for( QuestionSelectesEntity select : selectes){
				JSONObject jsSelect = new JSONObject();
				jsSelect.put("select", select.getSelectRe());
			   selectsArray.add(jsSelect);	
			}
			jsob.put("selects", selectsArray);
		}
		jb.put("questions", jsArray);
		jb.put("msg","预览已生成");
		jb.put("success",true);
		return jb;
	}
	
	
	/**
	 * @param id
	 * @param re
	 * @param response
	 * @return  创建问卷表
	 */
	@RequestMapping(params="createQustionTable")
	@ResponseBody
	public AjaxJson createQuestionTable(String id, HttpServletRequest re, HttpServletResponse response){
		 AjaxJson js = new AjaxJson();
		 String  mesg = "创建成功";
		 QuestionConfigEntity config = systemService.getEntity(QuestionConfigEntity.class, id);
		 //获取表名  标题
		 String tableName = config.getBy3();
		 String title = config.getBpmTitle();
		 //获取问题列表  生成表字段
		 ArrayList<String> questionList = new ArrayList<>();
		 ArrayList<String> selectList = new ArrayList<>();
		 List<TestQuestionEntity> questions = systemService.findHql(" from TestQuestionEntity where by1 ='"+config.getId()+"'");
		 for(int i= 0; i < questions.size(); i++){
			 questionList.add("ques_"+i);
			    TestQuestionEntity question = questions.get(i);
				List<QuestionSelectesEntity> selectes = systemService.findHql(" from QuestionSelectesEntity where by1 = '"+question.getId()+"'");
		        for( int j = 0; j < selectes.size(); j++){
		        	QuestionSelectesEntity select = selectes.get(j);
		        	selectList.add("ques_"+i+"_"+j);
		        }
		 }
		 //判断表是否存在
		 
		 
		 return js;
	}
	

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(QuestionConfigEntity questionConfig,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(QuestionConfigEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, questionConfig, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.questionConfigService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 删除问卷调查配置表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(QuestionConfigEntity questionConfig, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		questionConfig = systemService.getEntity(QuestionConfigEntity.class, questionConfig.getId());
		message = "问卷调查配置表删除成功";
		try{
			questionConfigService.delete(questionConfig);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "问卷调查配置表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除问卷调查配置表
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "问卷调查配置表删除成功";
		try{
			for(String id:ids.split(",")){
				QuestionConfigEntity questionConfig = systemService.getEntity(QuestionConfigEntity.class, 
				id
				);
				questionConfigService.delete(questionConfig);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "问卷调查配置表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加问卷调查配置表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "commitdate")
	@ResponseBody
	public AjaxJson doAdd(QuestionConfigEntity questionConfig, HttpServletRequest request,String questions, String title,String bpmTitle,String by3) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "问卷调查配置表添加成功";
		questionConfig.setBpmTitle(bpmTitle);
		questionConfig.setBy3(by3);
		try{
			questionConfigService.save(questionConfig);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "问卷调查配置表添加失败";
			throw new BusinessException(e.getMessage());
		}
		JSONArray queja = JSONObject.parseArray(questions);
		for(Object qu : queja){
			TestQuestionEntity quest = new TestQuestionEntity();
			String qure = JSONObject.parseObject(qu.toString()).getString("queRe");
			String qurTy = JSONObject.parseObject(qu.toString()).getString("queType");
			JSONArray array = JSONObject.parseObject(qu.toString()).getJSONArray("selects");
			quest.setQuestionRe(qure);
			quest.setQuestionType(Integer.parseInt(qurTy));
			quest.setBy1(questionConfig);
			//保存问题
			try {
				testQuestionS.save(quest);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for( Object select: array){
				QuestionSelectesEntity questionSelect = new QuestionSelectesEntity();
				String selectRe = JSONObject.parseObject(select.toString()).getString("questionRe");
				String selectAs = JSONObject.parseObject(select.toString()).getString("questionAs");
				questionSelect.setSelectRe(selectRe);
				questionSelect.setBy1(quest);
				questionSelect.setBy3(selectAs);
				try {
					questionSelectS.save(questionSelect);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			}
		
		}
		j.setMsg(message);
		return j;
	}
	
	
	
	/**
	 * 动态预览
	 * @param id
	 * @return
	 */
	@RequestMapping(params="createPage")
	@ResponseBody
	public AjaxJson createPage(String id){
		String content="";
		AjaxJson js = new AjaxJson();
		if( StringUtil.isEmpty(id)){
			js.setMsg("目前不可预览");
			js.setSuccess(false);
		}else{
			content="正在开发";
			js.setMsg(content);
			js.setSuccess(true);
		}
		return js;
	}
	
	
	public StringBuffer appJsp(){
		StringBuffer sfjsp = new StringBuffer();
		sfjsp.append("");
		return sfjsp;
	}
	
	
	/**
	 * 更新问卷调查配置表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(QuestionConfigEntity questionConfig, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "问卷调查配置表更新成功";
		QuestionConfigEntity t = questionConfigService.get(QuestionConfigEntity.class, questionConfig.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(questionConfig, t);
			questionConfigService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "问卷调查配置表更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 问卷调查配置表新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(QuestionConfigEntity questionConfig, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(questionConfig.getId())) {
			questionConfig = questionConfigService.getEntity(QuestionConfigEntity.class, questionConfig.getId());
			req.setAttribute("questionConfigPage", questionConfig);
		}
		return new ModelAndView("lv/questionConfig-add");
	}
	/**
	 * 问卷调查配置表编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(QuestionConfigEntity questionConfig, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(questionConfig.getId())) {
			questionConfig = questionConfigService.getEntity(QuestionConfigEntity.class, questionConfig.getId());
			req.setAttribute("questionConfigPage", questionConfig);
			//查询出所有问题
			List<TestQuestionEntity> questionList = systemService.findHql(" from TestQuestionEntity where by1.id = '"+questionConfig.getId()+"'");
			for(TestQuestionEntity quest: questionList){
				//req.setAttribute("", );
				List<QuestionSelectesEntity> selectList = systemService.findHql(" from QuestionSelectesEntity where by1.id = '"+quest.getId()+"'");
				//问题选项
				req.setAttribute("selectList", selectList);
			}
		}
		return new ModelAndView("lv/questionConfig-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","questionConfigController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(QuestionConfigEntity questionConfig,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(QuestionConfigEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, questionConfig, request.getParameterMap());
		List<QuestionConfigEntity> questionConfigs = this.questionConfigService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"问卷调查配置表");
		modelMap.put(NormalExcelConstants.CLASS,QuestionConfigEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("问卷调查配置表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,questionConfigs);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(QuestionConfigEntity questionConfig,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"问卷调查配置表");
    	modelMap.put(NormalExcelConstants.CLASS,QuestionConfigEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("问卷调查配置表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<QuestionConfigEntity> listQuestionConfigEntitys = ExcelImportUtil.importExcel(file.getInputStream(),QuestionConfigEntity.class,params);
				for (QuestionConfigEntity questionConfig : listQuestionConfigEntitys) {
					questionConfigService.save(questionConfig);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<QuestionConfigEntity> list() {
		List<QuestionConfigEntity> listQuestionConfigs=questionConfigService.getList(QuestionConfigEntity.class);
		return listQuestionConfigs;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		QuestionConfigEntity task = questionConfigService.get(QuestionConfigEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody QuestionConfigEntity questionConfig, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<QuestionConfigEntity>> failures = validator.validate(questionConfig);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		try{
			questionConfigService.save(questionConfig);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseEntity(HttpStatus.NO_CONTENT);
		}
		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		String id = questionConfig.getId();
		URI uri = uriBuilder.path("/rest/questionConfigController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> update(@RequestBody QuestionConfigEntity questionConfig) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<QuestionConfigEntity>> failures = validator.validate(questionConfig);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		try{
			questionConfigService.saveOrUpdate(questionConfig);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseEntity(HttpStatus.NO_CONTENT);
		}

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") String id) {
		questionConfigService.deleteEntityById(QuestionConfigEntity.class, id);
	}
	
	
	
}
